package com.konsung.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.konsung.bean.FlagModel;
import com.konsung.bean.PatientBean;
import com.konsung.healthfile.R;
import com.konsung.kslibrary.base.BaseActivity;
import com.konsung.kslibrary.base.MvpView;
import com.konsung.presenter.PatientDownloadPresenter;
import com.konsung.presenter.impl.PatientDownloadPresenterImpl;
import com.konsung.ui.adapter.PatienDownloadListAdapter;
import com.konsung.ui.adapter.PopupWindowAdapter;
import com.konsung.ui.defineview.UploadAllProgressDialog;
import com.konsung.util.BroadcastUtils;
import com.konsung.util.ToastUtils;
import com.konsung.util.UiUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.konsung.util.constant.GlobalConstant.IDCARD;

/**
 * Created by xiangshicheng on 2018/12/11 0011.
 * 居民下载类
 */

public class PatientDownloadActivity extends BaseActivity<PatientDownloadPresenterImpl>
        implements PatientDownloadPresenter.View, MvpView, View.OnClickListener
        , CompoundButton.OnCheckedChangeListener {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.et_query_condition)
    EditText etSearch;
    @BindView(R.id.iv_clear)
    ImageView ivClear;
    @BindView(R.id.iv_query)
    ImageView ivQuery;
    @BindView(R.id.tv_total)
    TextView tvTotalNum;
    @BindView(R.id.btn_download)
    Button btnDownload;
    @BindView(R.id.tv_had_choose_num)
    TextView tvHadChooseNum;
    @BindView(R.id.cbx_all_select)
    CheckBox cbCheckAll;
    @BindView(R.id.lv_patient_list)
    ListView lvPatient;
    @BindView(R.id.btn_page_first)
    Button btnFirst;
    @BindView(R.id.btn_page_pre)
    Button btnPre;
    @BindView(R.id.btn_page_number)
    TextView tvPageNum;
    @BindView(R.id.btn_page_next)
    Button btnPageNext;
    @BindView(R.id.btn_page_last)
    Button btnPageLast;
    @BindView(R.id.blank_page_show_tv)
    TextView tvBlank;
    public static final int PAGE_LIMIT = 5; //每页数量限制
    public static final int ALL_PAGE_LIMIT = 100; //下载所有情形下，每一次下载100条
    private PatienDownloadListAdapter adapter;
    private int currentPage = 1; //当前页数 默认为第一页
    private String condition = ""; //查询条件
    private boolean isFirstInPage = true; //记录首次在该页面调用查询接口
    private int allPage; //总共多少条数据
    private int totalPageNum; //总共多少页数
    private int requestCount; //下载全部所需要请求次数
    private UploadAllProgressDialog uploadAllProgressDialog;
    //全部下载判断(是否取消下载)
    public static boolean isStopDownload = false;
    private List<PatientBean> handCancelList = new ArrayList<>();; //用户手动取消掉的用户集合
    private List<PatientBean> selectPatientList = new ArrayList<>(); //记录批量选择的数据集合
    private boolean isCheckAll = false; //是否全选状态
    private boolean isCancelItemAtAll = false; //判断是否全选状态下取消了某个ITEM


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_patient_download);
        ButterKnife.bind(this);
        initView();
        initData();
        initEvent();
        initReceiver();
    }

    /**
     * 视图初始化
     */
    private void initView() {
        btnFirst.setEnabled(false);
        btnPre.setEnabled(false);
        btnPageNext.setEnabled(false);
        btnPageLast.setEnabled(false);
        tvPageNum.setEnabled(false);
        tvPageNum.setText("0");
    }

    /**
     * 数据初始化
     */
    private void initData() {
        //初始化默认0
        tvHadChooseNum.setText(getString(R.string.had_choose_patient_num, "0"));
        tvTotalNum.setText(getString(R.string.total_patient_num, "0"));
        adapter = new PatienDownloadListAdapter(this, null);
        lvPatient.setAdapter(adapter);
        isFirstInPage = true;
        adapter.setValue(true);
        presenter.queryPatient(condition, currentPage);
    }

    /**
     * 监听事件初始化
     */
    private void initEvent() {
        ivBack.setOnClickListener(this);
        cbCheckAll.setOnCheckedChangeListener(this);
        tvPageNum.setOnClickListener(this);
        btnFirst.setOnClickListener(this);
        btnPre.setOnClickListener(this);
        btnPageNext.setOnClickListener(this);
        btnPageLast.setOnClickListener(this);
        btnDownload.setOnClickListener(this);
        ivQuery.setOnClickListener(this);
        ivClear.setOnClickListener(this);
        //修改键盘的enter键，点击消费
        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
                if (actionId == EditorInfo.IME_NULL) {
                    //点击enter键搜索结果
                    currentPage = 1;
                    condition = etSearch.getText().toString();
                    isFirstInPage = true;
                    adapter.setValue(true);
                    presenter.queryPatient(condition, currentPage);
                    return true;
                }
                return false;
            }
        });
    }

    /**
     * 注册广播
     */
    private void initReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BroadcastUtils.HEALRH_MEASURE_CARD_READER);
        registerReceiver(broadcastReceiver, intentFilter);
    }

    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case BroadcastUtils.HEALRH_MEASURE_CARD_READER:
                    //接受到刷身份证后的广播
                    String idcard = intent.getStringExtra(IDCARD); //读取到的身份证号
                    condition = idcard;
                    etSearch.setText(idcard);
                    currentPage = 1;
                    isFirstInPage = true;
                    adapter.setValue(true);
                    presenter.queryPatient(idcard, currentPage);
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        BroadcastUtils.sendHideForStartManage();
    }

    @Override
    public PatientDownloadPresenterImpl initPresenter() {
        return new PatientDownloadPresenterImpl();
    }

    @Override
    public void onClick(View view) {
        int id  = view.getId();
        switch (id) {
            case R.id.iv_back:
                //页面返回
                finish();
                break;
            case R.id.btn_page_number:
                //点击页数弹窗
                ArrayList<String> datas = new ArrayList<>();
                for (int i = 1; i <= totalPageNum; i++) {
                    if (i < 10) {
                        datas.add("0" + i);
                    } else {
                        datas.add(i + "");
                    }
                }
                initPopWindow(datas, view);
                break;
            case R.id.btn_page_first:
                //首页点击
                currentPage = 1;
                btnFirst.setEnabled(false);
                btnPre.setEnabled(false);
                btnPageLast.setEnabled(true);
                btnPageNext.setEnabled(true);
                isFirstInPage = false;
                adapter.setValue(true);
                presenter.queryPatient(condition, currentPage);
                break;
            case R.id.btn_page_pre:
                //上一页
                if (currentPage - 1 < 1) {
                    return;
                }
                currentPage --;
                if (currentPage <= 1) {
                    btnFirst.setEnabled(false);
                    btnPre.setEnabled(false);
                } else {
                    btnFirst.setEnabled(true);
                    btnPre.setEnabled(true);
                }
                btnPageLast.setEnabled(true);
                btnPageNext.setEnabled(true);
                isFirstInPage = false;
                adapter.setValue(true);
                presenter.queryPatient(condition, currentPage);
                break;
            case R.id.btn_page_next:
                //下一页
                if (currentPage + 1 > totalPageNum) {
                    return;
                }
                currentPage ++;
                if (currentPage >= totalPageNum) {

                    btnPageLast.setEnabled(false);
                    btnPageNext.setEnabled(false);
                } else {
                    btnPageLast.setEnabled(true);
                    btnPageNext.setEnabled(true);
                }
                btnFirst.setEnabled(true);
                btnPre.setEnabled(true);
                isFirstInPage = false;
                adapter.setValue(true);
                presenter.queryPatient(condition, currentPage);
                break;
            case R.id.btn_page_last:
                //尾页
                btnFirst.setEnabled(true);
                btnPre.setEnabled(true);
                btnPageNext.setEnabled(false);
                btnPageLast.setEnabled(false);
                //如果网络没链接或者没有数据
                if (totalPageNum == 0) {
                    tvPageNum.setText("1");
                    btnFirst.setEnabled(false);
                } else {
                    currentPage = totalPageNum;
                    if (currentPage <= 1) {
                        btnFirst.setEnabled(false);
                        btnPre.setEnabled(false);
                    } else {
                        btnFirst.setEnabled(true);
                        btnPre.setEnabled(true);
                    }
                    isFirstInPage = false;
                    adapter.setValue(true);
                    presenter.queryPatient(condition, currentPage);
                }
                break;
            case R.id.btn_download:
                //下载
                boolean isCheckAll = this.isCheckAll;
                if (isCheckAll) {
                    if (allPage <= 0) {
                        ToastUtils.showShortToast(getString(R.string.download_patient_empty));
                        return;
                    }
                    if (allPage % PAGE_LIMIT > 0) {
                        requestCount = allPage / ALL_PAGE_LIMIT + 1;
                    } else {
                        requestCount = allPage / ALL_PAGE_LIMIT;
                    }
                    //如果是全选，数据超过100
                    uploadAllProgressDialog = new UploadAllProgressDialog(this,
                            new UploadAllProgressDialog.UpdataButtonState() {
                                @Override
                                public void cancelUpload() {
                                    isStopDownload = true;
                                }
                            });
                    uploadAllProgressDialog.show();
                    uploadAllProgressDialog.setText(UiUtils.getString(R.string.cancel_download),
                            UiUtils.getString(R.string.data_downloading));
                    presenter.queryAllPatient(condition, 0);
                    FlagModel.getInstance().isDownloadData = true;
                } else {
                    //单项选择的用户
                    if (selectPatientList.size() > 0) {
                        FlagModel.getInstance().isDownloadData = true;
                    }
                    presenter.downloadSelectData(selectPatientList);
                }
                break;
            case R.id.iv_query:
                currentPage = 1;
                condition = etSearch.getText().toString();
                isFirstInPage = true;
                adapter.setValue(true);
                presenter.queryPatient(condition, currentPage);
                break;
            case R.id.iv_clear:
                etSearch.setText("");
                break;
            default:
                break;
        }
    }

    @Override
    public void showPatientList(List<PatientBean> beanList, String num) {
        //每次查询完后调用该方法显示页面数据
        if (beanList != null && beanList.size() > 0) {
            lvPatient.setVisibility(View.VISIBLE);
            tvBlank.setVisibility(View.GONE);
            tvBlank.setEnabled(true);
            adapter.setDatas(beanList);
            allPage = Integer.valueOf(num);
            if (allPage % PAGE_LIMIT > 0) {
                totalPageNum = allPage / PAGE_LIMIT + 1;
            } else {
                totalPageNum = allPage / PAGE_LIMIT;
            }
            tvPageNum.setText(currentPage + "/" + totalPageNum);
            tvTotalNum.setText(getString(R.string.total_patient_num, num));
            tvPageNum.setEnabled(true);
            if (isFirstInPage) {
                btnFirst.setEnabled(false);
                btnPre.setEnabled(false);
                btnPageNext.setEnabled(true);
                btnPageLast.setEnabled(true);
            }
        } else {
            lvPatient.setVisibility(View.GONE);
            tvBlank.setVisibility(View.VISIBLE);
            setPageEmpty();
        }
    }

    @Override
    public void updateAdapter() {
        adapter.notifyDataSetChanged();
    }

    @Override
    public void resetView() {
        adapter.setCheckAll(false);
        cbCheckAll.setChecked(false);
        //下载完成后的数据还原
        this.isCheckAll = false;
        adapter.setCheckAll(false);
        showHadChooseValue("0");
        selectPatientList.clear();
        handCancelList.clear();
    }

    @Override
    public void dismissDialog() {
        if (null != uploadAllProgressDialog) {
            uploadAllProgressDialog.dismiss();
        }
    }

    @Override
    public void updateDialog(int percentValue, int totalPage, int currentPage) {
        uploadAllProgressDialog.setProgress(percentValue);
        //最後一次請求后，彈窗消失
        if (totalPage >= allPage) {
            if (null != uploadAllProgressDialog) {
                uploadAllProgressDialog.dismiss();
            }
            //点击全部下载或者单点下载，下载完成后，设置还原
            adapter.setCheckAll(false);
            cbCheckAll.setChecked(false);
        } else {
            presenter.queryAllPatient(condition, currentPage + 1);
        }
    }

    @Override
    public void openDialog() {

    }

    /**
     * 全选状态下获取的用户手动取消数据集合
     * 获取手动取消掉的用户集合
     * @return 用户数据集合
     */
    public List<PatientBean> getHandCancelList() {
        return handCancelList;
    }

    /**
     * 设置全选状态下用户手动取消数据集合
     * @param patientBean 取消掉的数据
     * @param isSelect 是否选中
     */
    public void setHandCancelList(PatientBean patientBean, boolean isSelect) {
        isCancelItemAtAll = true;
        cbCheckAll.setChecked(false);
        changePatientByIdcard(handCancelList, patientBean, isSelect);
        if (isCheckAll) {
            Log.e("xsc_allpage", handCancelList.size() + "" + allPage);
            //全选的情况下
            if (allPage > 0) {
                int num = allPage - handCancelList.size();
                showHadChooseValue(num + "");
            }
        }
        isCancelItemAtAll = false;
    }

    /**
     * 根据身份证判断，1.移除时，相同身份证的数据去除掉，2.增加时相同身份证不增加
     * @param sourceList 源数据
     * @param patientBean 用户数据
     * @param isRemove true 移除数据 false 添加数据
     */
    private void changePatientByIdcard(List<PatientBean> sourceList
            , PatientBean patientBean, boolean isRemove) {
        //集合中间变量，用于存储需删除数据集合
        List<PatientBean> tempList = new ArrayList<>();
        if (isRemove) {
            if (sourceList != null && sourceList.size() > 0) {
                for (PatientBean patientBean1 : sourceList) {
                    if (patientBean1.getIdcard().equals(patientBean.getIdcard())) {
                        tempList.add(patientBean1);
                    }
                }
                sourceList.removeAll(tempList);
            }
        } else {
            List<String> idCardList = new ArrayList<>();
            for (PatientBean patientBean1 : sourceList) {
                idCardList.add(patientBean1.getIdcard());
            }
            if (!idCardList.contains(patientBean.getIdcard())) {
                sourceList.add(patientBean);
            }
        }
    }

    /**
     * 将底部按钮设置为不可点击
     */
    private void setPageEmpty() {
        allPage = 0;
        btnFirst.setEnabled(false);
        btnPre.setEnabled(false);
        btnPageNext.setEnabled(false);
        btnPageLast.setEnabled(false);
        tvPageNum.setEnabled(false);
        tvPageNum.setText("0");
        tvHadChooseNum.setText(getString(R.string.had_choose_patient_num, "0"));
        tvTotalNum.setText(getString(R.string.total_patient_num, "0"));
    }

    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
        if (!isCancelItemAtAll) {
            this.isCheckAll = isChecked;
            adapter.setCheckAll(isChecked);
            if (isChecked) {
                showHadChooseValue(allPage + "");
            } else {
                showHadChooseValue("0");
            }
            selectPatientList.clear();
            handCancelList.clear();
        }
    }

    /**
     * 显示已选多少条记录数值
     * @param num 数值
     */
    public void showHadChooseValue(String num) {
        tvHadChooseNum.setText(getString(R.string.had_choose_patient_num, num));
        if (!TextUtils.isEmpty(num)) {
            if (Integer.valueOf(num) == allPage) {
                cbCheckAll.setChecked(true);
            } else {
                cbCheckAll.setChecked(false);
            }
        }
    }

    /**
     * 从云南1.0.1合并过来的选择页面
     *
     * @param name 姓名集合
     * @param view 视图
     */
    private void initPopWindow(ArrayList<String> name, View view) {

        View contentView = LayoutInflater.from(this.getApplicationContext())
                .inflate(R.layout.popupwindow_page, null);

        final PopupWindow popupWindow = new PopupWindow(1300, 350);
        popupWindow.setContentView(contentView);

        TextView textView = (TextView) contentView.findViewById(R.id.pop_title);
        textView.setText(UiUtils.getString(R.string.select_page_number));
        ListView listView = (ListView) contentView.findViewById(R.id.pop_list);
        PopupWindowAdapter popAdapter = new PopupWindowAdapter(this, name);
        listView.setAdapter(popAdapter);
        popupWindow.setTouchable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0xb0000000));
        popupWindow.setFocusable(true);
        popupWindow.showAsDropDown(view);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                String strPageNumber = (i + 1) + "";
                if (strPageNumber == null || strPageNumber.equals("0")) {
                    //当前页默认1
                    currentPage = 1;
                    tvPageNum.setText(currentPage + "");
                } else {
                    //选择当前页
                    currentPage = Integer.valueOf(strPageNumber);
                    tvPageNum.setText(strPageNumber + "/" + totalPageNum);
                }
                if (currentPage <= 1) {
                    //首页
                    btnFirst.setEnabled(false);
                    btnPre.setEnabled(false);
                    btnPageNext.setEnabled(true);
                    btnPageLast.setEnabled(true);
                } else if (currentPage >= totalPageNum) {
                    //末页
                    btnFirst.setEnabled(true);
                    btnPre.setEnabled(true);
                    btnPageNext.setEnabled(false);
                    btnPageLast.setEnabled(false);
                } else {
                    btnFirst.setEnabled(true);
                    btnPre.setEnabled(true);
                    btnPageNext.setEnabled(true);
                    btnPageLast.setEnabled(true);
                }
                adapter.setValue(true);
                presenter.queryPatient(condition, currentPage);
                popupWindow.dismiss();
            }
        });
    }

    /**
     * 记录批量选择时候的数据
     * @param patient 用户
     * @param isSelect 是否选择了该用户
     */
    public void setSelectPatient(PatientBean patient, boolean isSelect) {
        changePatientByIdcard(selectPatientList, patient, !isSelect);
        showHadChooseValue(selectPatientList.size() + "");
    }

    /**
     * 获取批量选择的用户数据
     * @return 批量选择的用户数据
     */
    public List<PatientBean> getSelectPatientList() {
        return selectPatientList;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(broadcastReceiver);
    }
}
